
from flask import jsonify
from flask_restful import Resource, Api

import os
import sys
import six
from inspect import getmembers, isclass

# 抽象一个公共的API接口视图
class APIView(Resource):
    # method_decorators = [auth_required]

    def __init__(self):
        super(APIView, self).__init__()

    # 装饰器标记为静态方法，不需要实例化类即可调用，如APIView.jsonify(...)
    # 返回json格式的响应
    @staticmethod
    def jsonify(*args, **kwargs):
        return jsonify(*args, **kwargs)
    

# resource_path：需要自动注册的Resource的文件夹
def register_resources(resource_path, rest_api: Api):
    """
    注册资源
    """
    excludes = ['account.py', 'entry.py']
    for dirpath, dirnames, filenames in os.walk(os.path.join(resource_path)):
        print("原始数据：")
        print(dirpath)
        print(dirnames)
        print(filenames)
        for filename in filenames:
            if not filename.startswith('_') and filename.endswith('py') and filename not in excludes:
                print(f"处理的文件是: {filename}")
                if dirpath not in sys.path:
                    sys.path.insert(1, dirpath)
                # 导入每个文件
                view = __import__(os.path.splitext(filename)[0])
                resource_list = [obj[0] for obj in getmembers(view) if isclass(obj[1]) and issubclass(obj[1], Resource)]
                resource_list = [res for res in resource_list if res not in ('APIView', 'Resource')]
                print(f"获取的接口资源类名为：{resource_list}")
                # 处理每一个接口资源
                for resource_cls_name in resource_list:
                    resource_cls = getattr(view, resource_cls_name)
                    if not hasattr(resource_cls, 'url_prefix'):
                        resource_cls.url_prefix = ("",)
                    if isinstance(resource_cls.url_prefix, six.string_types):
                        resource_cls.url_prefix = (resource_cls.url_prefix,)
                    rest_api.add_resource(resource_cls, *resource_cls.url_prefix)
                
                                  
    	
